package com.cortex.papaya.search;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

import org.carrot2.clustering.lingo.LingoClusteringAlgorithm;
import org.carrot2.core.Cluster;
import org.carrot2.core.Controller;
import org.carrot2.core.ControllerFactory;
import org.carrot2.core.Document;
import org.carrot2.core.ProcessingResult;
import org.carrot2.source.SearchEngineResponse;

import com.cortex.papaya.search.FetchData.OnStateDataChanged;
import com.cortex.papaya.utilities.Colors;
import com.cortex.papaya.utilities.MyLog;
import com.cortex.papayasearch.R;

import android.os.AsyncTask;
import android.util.Log;

public class Categories {

	private List<Category> categories;
	private Category selectedCategory;
	private Link selectedLink;
	private static List<Integer> colorsUsed;
	private OnStateCategoriesChangedListener onStateCategoriesChangedListener;
	private List<Document> allDocuments;
	private String query;

	public Categories(){
		categories = new ArrayList<Category>();
		colorsUsed = new ArrayList<Integer>();
	}
	public void runBuildCategories(List<Document> allDocuments,String query){
		this.allDocuments = allDocuments;
		this.query = query;
		new StartCategoriesThread().execute();
	}
	public void setOnStateCategoriesChangedListener(
			OnStateCategoriesChangedListener onStateCategoriesChangedListener) {
		this.onStateCategoriesChangedListener = onStateCategoriesChangedListener;
	}
	public List<Link> getAllLinks(){
		return categories.get(0).getLinks();
	}
	public Link getLinkByUrl(String url){
		for (Link document : getAllLinks()) {
			if(document.getUrl().equals(url)){
				return document;
			}
		}
		return null;
	}
	public List<Category> getCategories() {
		return categories;
	}
	public boolean isEmpty(){
		return categories.isEmpty();
	}
	public void setSelectedCategory(Category selectedCategory) {
		this.selectedCategory = selectedCategory;
	}
	public Category getSelectedCategory() {
		return selectedCategory;
	}
	public void setSelectedLink(Link selectedLink) {
		this.selectedLink = selectedLink;
	}
	public Link getSelectedLink() {
		return selectedLink;
	}
	public static int getRandomResourceColor(){
		int color;
		if(colorsUsed.size() == Colors.colorsSize()){
			colorsUsed.clear();
		}
		do{
			color = Colors.getRandomResourceColor();
		}while(colorsUsed.contains(color));
		colorsUsed.add(color);
		return color;
	}

	private class StartCategoriesThread extends AsyncTask<Void, String, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			try {
				buildCategoriesByQuerySearch();
			} catch (Exception e) {
				publishProgress("you have a problem with search");
			}
			return null;
		}
		@Override
		protected void onProgressUpdate(String... values) {
			if(onStateCategoriesChangedListener != null){
				onStateCategoriesChangedListener.timeLoadBuiltCanceled(values[0]);
			}
		}
		@Override
		protected void onPostExecute(Void result) {
			if(onStateCategoriesChangedListener != null){
				onStateCategoriesChangedListener.timeLoadBuiltFinished();
			}
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
			if(onStateCategoriesChangedListener != null){
				onStateCategoriesChangedListener.timeLoadBuiltCanceled("build categories canceled");
			}
		}
		private void buildCategoriesByQuerySearch(){
			categories.clear();
			if(allDocuments != null){
				Controller controller = ControllerFactory.createSimple();
				/* Perform processing */
				controller.init();
				ProcessingResult categoriesResults = controller.process(allDocuments, query,
						LingoClusteringAlgorithm.class);


				List<Link> allPapayaDocuments = new ArrayList<Link>();
				for (Document document : allDocuments) {
					allPapayaDocuments.add(new Link(document));
				}
				// add all results category
				categories.add(new Category("All Results",categoriesResults.getClusters().get(0),allPapayaDocuments));
				Category allResults = categories.get(0);
				
				// convert all documents of all clusters to all PapayaDocuments of all PapayaCategories
				for (Cluster cluster : categoriesResults.getClusters()) {
					List<Link> documents = new ArrayList<Link>();
					for (Document document : cluster.getDocuments()) {
						int id = document.getId();
						Link doc = allResults.getLink(id);
						if(doc != null){
							documents.add(doc);

						}
					}
					categories.add(new Category(cluster.getLabel(),cluster, documents));
				}
			}
			selectedCategory = categories.get(0);
		}
	}

	public interface OnStateCategoriesChangedListener{
		void timeLoadBuiltStarted();
		void timeLoadBuiltFinished();
		void timeLoadBuiltCanceled(String message);
	}
}
